<!--组件模板-->
<template>
 <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
    <el-form-item label="供应商" prop="sId">
        <el-select v-model="queryParams.sId" placeholder="请选择供应商名称">
          <el-option
            v-for="item in suppliersList"
            :key="item.sId"
            :label="item.sName"
            :value="item.sId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="需求机构" prop="agencyId">
        <el-select v-model="queryParams.agencyId" placeholder="请选择机构名称">
          <el-option
            v-for="item in agencyList"
            :key="item.agencyId"
            :label="item.agencyName"
            :value="item.agencyId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="规格" prop="specs">
        <el-input
          v-model="queryParams.specs"
          placeholder="请输入规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="通过时间" prop="passTime">
        <el-date-picker
          clearable
          v-model="queryParams.passTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择通过时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
    ></right-toolbar>
    <el-table
      v-loading="loading"
      :data="vettingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="供应商" align="center" prop="sName" />
      <el-table-column label="机构" align="center" prop="agencyName" />
      <el-table-column label="规格" align="center" prop="specs" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column
        label="通过时间"
        align="center"
        prop="passTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.passTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> 

      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <!-- 根据scope.row.status的值来显示对应的文字 -->
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </div>
</template>

<!--组件逻辑-->
<script>
import { listRecord,getRecord } from "@/api/agency/record"
export default {
  name: "Vetting",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批表格数据
      vettingList: [],
      suppliersList: [], // 供应商列表
      agencyList: [], // 机构列表
      demandList: [], // 需求列表
      selectedQuantity: null, // 用于存储选中的数量
      // 初始状态值（可以从后端获取）
      statusMap: [
        { dictValue: 0, dictLabel: "待匹配" },
        { dictValue: 1, dictLabel: "已匹配" },
        { dictValue: 2, dictLabel: "已取消" },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sId: null,
        reqId: null,
        agencyId: null,
        passTime: null,
        endTime: null,
        status: null,
        statusText: "", // 存储状态文字（用于显示）
      },
      // 表单参数
      form: {
        agencyId: null,
        reqId: null,
      },
      displayForm: {
        // 用于显示的数据，可以是 form 的一个副本或映射
        sName: '',
        // 其他字段...
      },
      agencyName: '',
      specs: '',
      endTime: '',
      isFormVisible : false, // 控制是否显示编辑框的条件
      isHide:true,
      // 表单校验
      rules: {
        sId: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
        reqId: [{ required: true, message: "需求不能为空", trigger: "blur" }],
        agencyId: [
          { required: true, message: "机构不能为空", trigger: "blur" },
        ],
        // passTime: [
        //   { required: true, message: "通过时间不能为空", trigger: "blur" },
        // ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getList();
    this.getSuppliersList();
    this.getAgencyList();
   
  },
  methods: {
    /**按状态值渲染对应状态 */
    getStatusText(status) {
      const statusMap = {
        0: "待匹配",
        1: "已匹配",
        2: "已取消",
        // ...更多状态映射
      };
      return statusMap[status] || "未知状态"; // 如果status不在statusMap中，返回'未知状态'
    },
    /** 查询供应商信息列表 */
    getSuppliersList() {
      listSuppliers()
        .then((response) => {
          this.suppliersList = response.rows;
        })
        .catch((error) => {
          console.error("获取供应商列表失败:", error);
          // 这里可以处理错误，比如显示一个错误消息
        });
    },

    /** 查询机构信息列表 */
    getAgencyList() {
      listManage()
        .then((response) => {
          this.agencyList = response.rows;
        })
        .catch((error) => {
          console.error("获取机构列表失败:", error);
          // 这里可以处理错误，比如显示一个错误消息
        });
    },

    getDemandList(agencyId) {
      // 根据选中的机构ID从后端获取需求列表
      listDemand({ agencyId }).then((response) => {
        const filteredDemandList = response.rows.filter(
          (demand) => demand.status !== 1
        ); // 过滤掉 status 等于 1 的数据

        this.demandList = filteredDemandList;
      });
    },

    handleAgencyChange(value) {
      // 当机构下拉框的值变化时，调用此方法
      this.demandList = []; // 先清空需求列表，避免显示旧数据
      if (value) {
        // 如果选中的机构ID存在，则获取对应的需求列表
        this.getDemandList(value);
      }
    },
    updateQuantity(value) {
      // 当选择变化时，找到对应的数量并更新 selectedQuantity
      const selectedItem = this.demandList.find((item) => item.reqId === value);
      if (selectedItem) {
        this.selectedQuantity = selectedItem.quantity;
      } else {
        this.selectedQuantity = null; // 或者设置为某个默认值，比如 0
      }
    },

    mounted() {
      this.getAgencyList(); // 在组件挂载时获取机构列表
    },

    /** 查询审批列表 */
    getList() {
      this.loading = true;
      listRecord(this.queryParams).then((response) => {
        this.vettingList = response.rows;
        this.total = response.total;        
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isFormVisible = false;
      this.isHide=true;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sId: null,
        reqId: null,
        agencyId: null,
        passTime: null,
        endTime: null,
      };
      this.selectedQuantity = null;
      // 清空需求列表，避免值残留
      this.demandList = [];
      this.isFormVisible = false;
      this.isHide=true;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isFormVisible = false;
      this.isHide=true;
      this.open = true;
      this.title = "添加审批";
    },
    /** 审批按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRecord(id).then((response) => {
        this.form = response.data;
        console.log(this.form);
        // 映射或复制数据到 displayForm
        this.selectedQuantity=this.form.quantity;
        this.displayForm.sName = this.form.sName;
        this.agencyName =this.form.agencyName;
        this.specs =this.form.specs;
        this.endTime =this.form.endTime;
        this.isFormVisible = true;
        this.isHide= false;
        this.open = true;
        this.title = "审批";
      });
    },
    /** 审批按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids;
    //   getVetting(id).then((response) => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改审批";
    //   });
    // },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            // updateDemand(this.form).then((response) => {
            updateVetting(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVetting(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除审批编号为"' + ids + '"的数据项？')
        .then(function () {
          return delVetting(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "lobby/vetting/export",
        {
          ...this.queryParams,
        },
        `vetting_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<!--组件样式-->
<style>
</style>